using System;
using System.DHTML;
using Sys;
using Sys.UI;

using JQuerySharp;
using VietPublisher.Scripts.Resources;

public delegate void HandleClickDelegate();
public delegate void GenericOneArgDelegate(object arg1);

static public class Utils
{
    private const string FILE_NAME_PATTERN = "^(.*?)(\\\\|/)*([^\\\\/]+)(\\\\|/)*$";
    static private RegularExpression FILE_NAME_REG = new RegularExpression(FILE_NAME_PATTERN, "ig");
    static private RegularExpression SERVERURL_REG = new RegularExpression(@"^http:\/\/((\w+)(\.\w+)*)(:\d+)?(\/\w+)?(\/[\w-]+)?(\?(.*))?", "ig");

    static public string GetFileName(string fileName)
    {
        if (fileName == null || fileName == "") return "";
        string[] result = fileName.Match(FILE_NAME_REG);
        return Type.GetField(typeof(RegularExpression), "$3").ToString();
    }

    static public string GetPath(string fileName)
    {
        string[] result = fileName.Match(FILE_NAME_REG);
        return Type.GetField(typeof(RegularExpression), "$1").ToString();
    }

    static public string GetHost(string url)
    {
        url.Match(SERVERURL_REG);
        Dictionary RegObj = (Dictionary)(object)typeof(RegularExpression);
        return "http://" + (string)RegObj["$1"] + (string)RegObj["$4"];
    }

    static public string GetServerPath(string url)
    {
        url.Match(SERVERURL_REG);
        Dictionary RegObj = (Dictionary)(object)typeof(RegularExpression);
        return (string)RegObj["$1"];
    }

    static public string GetController(string url)
    {
        url.Match(SERVERURL_REG);
        Dictionary RegObj = (Dictionary)(object)typeof(RegularExpression);
        return ((string)RegObj["$5"]).Replace("/", "");
    }

    static public string GetAction(string url)
    {
        url.Match(SERVERURL_REG);
        Dictionary RegObj = (Dictionary)(object)typeof(RegularExpression);
        return ((string)RegObj["$6"]).Replace("/", "");
    }

    #region GetQueryString cua triet
    static public string GetQueryString2(string url, string name)
    {
        string[] query = url.Split('?');
        string queryString = query[1];
        string[] items = queryString.Split(new RegularExpression("=|&"));
        int count = items.Length;
        for (int i = 0; i < count; i++)
        {
            string item = items[i];
            if (item != null && item.ToLowerCase() == name.ToLowerCase() && i < count - 1)
            {
                return (string)Script.Literal("unescape(items[i+1])");
            }
        }
        return "";
    }
    #endregion
    #region GetQueryString cua anh Ngoc
    //This Code oF Ngoc
    static public string GetQueryString(string url, string name)
    {
        url.Match(SERVERURL_REG);
        Dictionary RegObj = (Dictionary)(object)typeof(RegularExpression);
        string queryString = ((string)RegObj["$8"]).Replace("/", "");

        string[] items = queryString.Split(new RegularExpression("=|&"));
        int count = items.Length;
        for (int i = 0; i < count; i++)
        {
            string item = items[i];
            if (item != null && item.ToLowerCase() == name.ToLowerCase() && i < count - 1)
            {
                return (string)Script.Literal("unescape(items[i+1])");
            }
        }
        return "";
    }
    #endregion

    static public string GenerateGuid()
    {
        string result = "";
        string i;
        for (int j = 0; j < 32; j++)
        {
            if ((j == 8) || (j == 12) || (j == 16) || (j == 20))
            {
                result = result + '-';
            }
            i = Math.Floor(Math.Random() * 16).ToString(16).ToUpperCase();
            result = result + i;
        }
        return result;
    }

    static public string GetStringFromArray(string[] strArray)
    {
        string result = "";
        int count = strArray.Length;
        for (int i = 0; i < count; i++)
        {
            if (strArray[i] == null) continue;
            if (i != 0)
            {
                result += ",";
            }
            result += strArray[i];
        }

        return result;
    }

    public static Type GetType(string fullName)
    {
        string[] names = fullName.Split('.');
        int count = names.Length;
        Dictionary currentType = Dictionary.GetDictionary(typeof(Window));
        for (int i = 0; i < count; i++)
        {
            Dictionary dic = Dictionary.GetDictionary(currentType[names[i]]);
            if (dic != null)
            {
                currentType = dic;
            }
            else
            {
                return null;
            }
        }
        return (Type)(object)currentType;
    }

    public static string GetInputValue(string inputId)
    {
        return ((InputElement)Document.GetElementById(inputId)).Value;
    }

    public static void SetInputValue(string inputId, string value)
    {
        ((InputElement)Document.GetElementById(inputId)).Value = value;
    }

    public static string GetRadioButtonListValue(string inputId)
    {
        string rValue = "";
        DOMElementCollection col = Document.GetElementsByName(inputId);
        for (int i = 0; i < col.Length; i++)
        {
            CheckBoxElement input = (CheckBoxElement)col[i];
            if (input.Checked)
            {
                rValue = input.Value;
                break;
            }
        }

        return rValue;
    }

    public static string GetCheckBoxListValue(string inputId)
    {
        string rValue = "";
        DOMElementCollection col = Document.GetElementsByName(inputId);
        for (int i = 0; i < col.Length; i++)
        {
            CheckBoxElement input = (CheckBoxElement)col[i];
            if (input.Checked)
            {
                rValue += input.Value + "-";
            }
        }

        if (rValue.Length > 0)
        {
            rValue = rValue.Substr(0, rValue.Length - 1);
        }

        return rValue;
    }


    public static void LoadJavascript(string src, Callback scriptLoaded)
    {
        Type type = GetType("ajaxObject");
        object obj = Type.CreateInstance(type, src, scriptLoaded);
        Type.InvokeMethod(obj, "update");
    }

    static public void LoadCssFile(string href)
    {
        DOMElement headerTag = Document.GetElementsByTagName("head")[0];
        DOMElement scriptTag = Document.CreateElement("script");
        scriptTag.SetAttribute("type", "text/css");
        scriptTag.SetAttribute("rel", "Stylesheet");
        scriptTag.SetAttribute("href", href);
        headerTag.AppendChild(scriptTag);
    }

    static public void LoadScriptFile(string src)
    {
        DOMElement headerTag = Document.GetElementsByTagName("head")[0];
        DOMElement scriptTag = Document.CreateElement("script");
        scriptTag.SetAttribute("type", "text/javascript");
        scriptTag.SetAttribute("src", src);
        headerTag.AppendChild(scriptTag);
    }

    static public string ReplaceTagHTML(string str)
    {
        RegularExpression regLess = new RegularExpression("<", "igm");
        RegularExpression regGreat = new RegularExpression(">", "igm");

        str = str.Replace(regLess, "&ltz;");
        str = str.Replace(regGreat, "&gtz;");
        return str;
    }

    static public string UnReplaceTagHTML(string str)
    {
        RegularExpression regLess = new RegularExpression("&ltz;", "igm");
        RegularExpression regGreat = new RegularExpression("&gtz;", "igm");

        str = str.Replace(regLess, "<");
        str = str.Replace(regGreat, ">");
        return str;
    }

    static public object RenderFileSize(object value)
    {
        if (value != null)
        {
            int size = (int)value;
            if (size < 1024) return string.Format("{0} Byte", size);
            size = Math.Round(size / 1024);
            if (size < 1024) return string.Format("{0} KB", size);
            size = Math.Ceil(size / 1024);
            return string.Format("{0} MB", size);
        }
        return null;
    }

    static public object FormatDate(object value)
    {
        DateTime time = (DateTime)Type.InvokeMethod(typeof(DateTime), "parseLocale", value, @"yyy-MM-ddTHH:mm:sszzz");
        //            return time.LocaleFormat(@"yy/MM/dd HH:mm:ss");            
        return time.LocaleFormat(@"dd/MM/yyyy HH:mm:ss");
    }

    static public string ParseToString(string value)
    {
        return (value == null || value == "undefined") ? "" : value;
    }

    static public bool IsNullOrEmpty(string value)
    {
        if (value == null || value == "" || value == "undefined")
        {
            return true;
        }
        return false;
    }

    static public bool IsNull(object value)
    {
        if (value == null || (string)value == "undefined")
        {
            return true;
        }

        return false;
    }

    static public void NumberMaker(string numElementId)
    {
        DOMElement element = Document.GetElementById(numElementId);
        if (element != null)
        {
            object value = Type.GetField(element, "value");
            if (value == null)
            {
                value = "0";
            }
            else
            {
                do
                {
                    value = value.ToString().Replace(",", "");
                } while (value.ToString().IndexOf(",", 0) != -1);
            }
            Type.SetField(element, "value", value);
        }
    }

    static public object ParseStrXMLtoXML(string xmlData)
    {
        return Script.Literal("ParseStrXMLtoXML(xmlData)");
    }


    static DomEvent _currentDomEvent = null;
    public static DomEvent SaveCurrentDomEvent()
    {
        if (Window.Event == null)
        {
            return _currentDomEvent;
        }
        _currentDomEvent = new DomEvent(Window.Event);
        return _currentDomEvent;
    }

    static public void HandleEnterKey(string btnSearchId)
    {
        if (Window.Event.KeyCode == 13)
        {
            try
            {
                DOMElement el = Document.GetElementById(btnSearchId);
                el.Click();
            }
            catch { }

        }
    }

    static public void ResizeViewer()
    {
        jQuery pic = new jQuery("#pathPic");

        int height = (int)(object)pic.Height() + 95;
        int width = (int)(object)pic.Width() + 20;
        if (height > Window.Screen.Height)
        {
            pic.Height(Window.Screen.Height);
            height = Window.Screen.Height;
        }
        if (width > Window.Screen.Width)
        {
            pic.Width(Window.Screen.Width);
            width = Window.Screen.Width;
        }

        Type.InvokeMethod(Document.ParentWindow, "resizeTo", width, height);
    }

    static public WindowInstance OpenWinCenter(string windowName, string url, int width, int height)
    {
        int left = (Window.Screen.AvailWidth - width) / 2;
        int top = (Window.Screen.AvailHeight - height) / 2;

        WindowInstance win = Window.Open(url, windowName, "menubar=0,statusbar=0,resizable=1,width=" + width.ToString() + ",height=" + height.ToString() + ",left=" + left.ToString() + ",top=" + top.ToString());
        Script.Literal("win.focus();");

        return win;
    }

    /// <summary>
    /// Open Pop with scrollbar
    /// </summary>
    /// <param name="windowName"></param>
    /// <param name="url"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    static public WindowInstance OpenWinCenterScroll(string windowName, string url, int width, int height)
    {
        int left = (Window.Screen.AvailWidth - width) / 2;
        int top = (Window.Screen.AvailHeight - height) / 2;

        WindowInstance win = Window.Open(url, windowName, "menubar=0,statusbar=0,resizable=1,scrollbars=1,width=" + width.ToString() + ",height=" + height.ToString() + ",left=" + left.ToString() + ",top=" + top.ToString());
        Script.Literal("win.focus();");

        return win;
    }

    static public WindowInstance OpenWinCenterScrollStatus(string windowName, string url, int width, int height)
    {
        int left = (Window.Screen.AvailWidth - width) / 2;
        int top = (Window.Screen.AvailHeight - height) / 2;

        WindowInstance win = Window.Open(url, windowName, "menubar=0,statusbar=1,resizable=1,scrollbars=1,width=" + width.ToString() + ",height=" + height.ToString() + ",left=" + left.ToString() + ",top=" + top.ToString());
        Script.Literal("win.focus();");

        return win;
    }

    static public WindowInstance OpenWinScroll(string windowName, string url, int width, int height)
    {
        WindowInstance win = Window.Open(url, windowName, "menubar=0,statusbar=0,resizable=1,scrollbars=1,width=" + width.ToString() + ",height=" + height.ToString());
        Script.Literal("win.focus();");

        return win;
    }

    static bool IsProcessing = false;
    static public void ShowProgressBarBlock()
    {
        if (IsProcessing)
        {
            Script.Alert(Common.InProcessingMsg);
            return;
        }

        IsProcessing = true;
        ShowProgressBar();
    }

    static public void ApplyNumericTextBox(string[] idArray, bool allowNegative, bool allowDecimal)
    {
        string selector = "";
        for (int i = 0; i < idArray.Length; i++)
        {
            selector += "#" + idArray[i] + ",";
        }
        if (selector != "")
        {
            selector = selector.Substring(0, selector.Length - 1);
        }


        JQueryFactory.JQuery(selector).jField(new Dictionary("allowNegative", allowNegative, "allowDecimal", allowDecimal));
        if (allowDecimal)
        {
            JQueryFactory.JQuery(selector).Blur(new Function("$(this).format({format:'#,###.00',locale:'us'})"));
        }
        else
        {
            JQueryFactory.JQuery(selector).Blur(new Function("$(this).format({format:'#,###',locale:'us'})"));
        }

        JQueryFactory.JQuery(selector).Focus((Function)(object)new BaseArgDelegate(delegate(Event e)
        {
            JQueryFactory.JQuery(e.SrcElement).Format(new Dictionary("format", "#", "locale", "us"));
            Type.InvokeMethod(e.SrcElement, "select");
        }));
    }

    static public void ApplyDecimalTextBox(string[] idArray, bool allowNegative, int decimalPoint)
    {
        string selector = "";
        for (int i = 0; i < idArray.Length; i++)
        {
            selector += "#" + idArray[i] + ",";
        }
        if (selector != "")
        {
            selector = selector.Substring(0, selector.Length - 1);
        }

        JQueryFactory.JQuery(selector).jField(new Dictionary("allowNegative", allowNegative, "allowDecimal", true));
        string zeroText = "";
        for (int i = 0; i < decimalPoint; i++)
        {
            zeroText += "0";
        }
        JQueryFactory.JQuery(selector).Blur(new Function(string.Format("$(this).format({format:'#,###.{0}',locale:'us'})", zeroText)));

        //JQueryFactory.JQuery(selector).Focus(new Function("$(this).format({format:'#',locale:'us'})"));
        JQueryFactory.JQuery(selector).Focus((Function)(object)new BaseArgDelegate(delegate(Event e)
        {
            JQueryFactory.JQuery(e.SrcElement).Format(new Dictionary("format", "#", "locale", "us"));
            Type.InvokeMethod(e.SrcElement, "select");
        }));
    }

    static public void ShowProgressBar()
    {
        string divTarget = "divAjaxProgressBar";

        jQuery jBody = JQueryFactory.JQuery("html body");
        DOMElement tagBody = (DOMElement)Script.Literal("jBody[0]");

        jQuery jDivPopup = JQueryFactory.JQuery("#" + divTarget);
        int countPopup = (int)Script.Literal("jDivPopup.length");
        if (countPopup == 0)
        {
            DOMElement divPopup = Document.CreateElement("div");
            divPopup.ID = divTarget;

            //int left = (tagBody.ClientWidth - 250) / 2;
            //int top = (tagBody.ClientHeight - 50) / 2;
            int left = (Window.Screen.AvailWidth - 250) / 2;
            int top = (Window.Screen.AvailHeight - 50) / 2;
            divPopup.Style.Left = left.ToString() + "px";
            divPopup.Style.Top = top.ToString() + "px";//top.ToString();
            tagBody.AppendChild(divPopup);
        }


        jQuery query = JQueryFactory.JQuery("#" + divTarget);
        JQueryFactory.JQuery("#" + divTarget).AddClass("u-loading-ajax");
        query.Show();

    }

    static public void HideProgressBar()
    {
        string divTarget = "divAjaxProgressBar";
        jQuery query = JQueryFactory.JQuery("#" + divTarget);
        query.RemoveClass("u-loading-ajax");
        query.Hide();
        IsProcessing = false;
    }

    static public string ShowProgressBarWithId()
    {
        string divTarget = "divAjaxProgressBarId";

        jQuery jBody = JQueryFactory.JQuery("html body");
        DOMElement tagBody = (DOMElement)Script.Literal("jBody[0]");

        jQuery jDivPopup = JQueryFactory.JQuery("div[name=divAjaxProgressBarId]");
        int countPopup = (int)Script.Literal("jDivPopup.length");

        if (countPopup != 0)
        {
            divTarget = divTarget + countPopup.ToString();            
        }

        DOMElement divPopup = Document.CreateElement("div");
        divPopup.ID = divTarget;
        divPopup.SetAttribute("name", "divAjaxProgressBarId");// = divTarget;

        int left = (tagBody.ClientWidth - 250) / 2;
        int top = (tagBody.ClientHeight - 50) / 2;
        divPopup.Style.Left = left.ToString() + "px";
        divPopup.Style.Top = top.ToString() + "px";//top.ToString();
        tagBody.AppendChild(divPopup);

        jQuery query = JQueryFactory.JQuery("#" + divTarget);
        JQueryFactory.JQuery("#" + divTarget).AddClass("u-loading-ajax");
        query.Show();

        return divTarget;

    }

    static public void HideProgressBarWithId(string divProgressId)
    {
        jQuery query = JQueryFactory.JQuery("#" + divProgressId);
        query.RemoveClass("u-loading-ajax");
        query.Hide();
        IsProcessing = false;
    }

    /// <summary>
    /// reload current window
    /// </summary>
    static public void ReloadWindow()
    {
        string url = Document.URL.Replace("#", "");
        Script.Literal("document.location.href = {0}", url);
    }

    static public void ReloadOpenerWindow()
    {
        if (Window.Opener != null)
        {
            string url = Window.Opener.Document.URL.Replace("#", "");
            Script.Literal("opener.document.location.href = {0}", url);
        }
    }

    static public void ReloadTopWindow()
    {
        try
        {
            if (Window.Top != null)
            {
                string url = Window.Top.Document.URL.Replace("#", "");
                Script.Literal("window.top.document.location.href = {0}", url);
            }
        }
        catch
        {
        }
    }

    static public void Navigate(string url)
    {
        Script.Literal("document.location.href = {0}", url);
    }

    static public void CloseWindow()
    {
        Window.SetTimeout("this.close();", 500);
    }

    public static void RequestByIframe(string href)
    {
        string divId = Utils.ShowProgressBarWithId();

        jQuery jIframe = JQueryFactory.JQuery("iframe[name=ifrmDownload]");
        int countIframe = (int)Script.Literal("jIframe.length");
        countIframe = countIframe + 1;
        string iframeName = "ifrmDownload" + countIframe.ToString();

        // create iframe
        IFrameElement iframe = (IFrameElement)Document.CreateElement("iframe");
        iframe.Style.Display = "none";
        iframe.SetAttribute("name", "ifrmDownload");
        iframe.ID = iframeName;

        Document.Body.AppendChild(iframe);
        iframe.Src = href;

        Script.Literal("HideDownloadIframe({0}, {1})", iframeName, divId);
    }

}
